package com.java.androidmarket.exception;

import com.java.androidmarket.entity.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * description:
 * author:张腾
 * date:2021-05-21
 */

@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ApiException.class)
    @ResponseBody
    public Result apiExceptionHandler(ApiException e){
        System.out.println("发生业务异常："+e.getErrorMsg());
        return Result.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(NullPointerException e){
        System.out.println("出现空指针异常："+e);
        return Result.error(CommonEnum.BODY_NOT_MATCH);
    }


    /**
     * 处理运行时异常等其他异常
     * @param e
     * @param req
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e, HttpServletRequest req){
        System.out.println("未知异常："+e);
        return Result.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

}
